const { Web3, HttpProvider } = require('web3');
const Big = require('big.js');

const QUICKNODE_RPC_URL =
    'https://sly-snowy-resonance.bsc.quiknode.pro/df130e3b4a962f23bc90ff2233d5fcb03315655e' // BSC 主网 RPC 节点
const contractABI = require("./common/abi.json");

async function initWeb3() {
    const provider = new HttpProvider(QUICKNODE_RPC_URL);
    const web3 = new Web3(provider);
    return web3;
}

const db = require("./common/mysql");
const redis = require("./common/redis").redis;
const config = require("./common/config").config;

async function getLatestBuyEvents() {
    try {
        const web3 = await initWeb3();

        const CONTRACT_ADDRESS = "0x8Cd25a51D29d629FD10ffFd693Af200581820FE7";
        const CONTRACT_ABI = contractABI

        const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
        const latestBlock = await web3.eth.getBlockNumber();
        // const fromBlock = '0x' + (latestBlock).toString(16);
        const fromBlock = new Big(latestBlock).sub(1000).toNumber()
        console.log(`Latest block number: ${latestBlock}`);
        console.log(`From block number: ${fromBlock}`);

        const events = await contract.getPastEvents("TransferCompleted", {
            fromBlock: fromBlock,
            toBlock: "latest"
        });

        // const latest10Events = events.slice(-100);
        console.log("Latest 1000 TransferCompleted Events:");
        const addressList = [];
        events.forEach((event, index) => {
            // console.dir(event);
            console.log(event.returnValues.sender);
            addressList.push("'" + event.returnValues.sender + "'");
            //console.log(`${index + 1}. event: ${str}`);
            // console.log(`${index + 1}. Buyer: ${event.returnValues.buyer}, Amount: ${event.returnValues.amount}`);
        });
        update(addressList);
    } catch (error) {
        console.error("Error fetching events:", error);
    }
}


const update = async (addressList) => {
    console.log("update state: ", addressList);
    const sql = "update app_user set state=1 where address in(" + addressList.join(",") + ")";
    // console.log("udpate sql: ", sql);
    db.query(sql, (error, results) => {
        if (error) {
            // 创建失败
            console.log(`update state error: \n ${sql}`);
        } else {
            // 创建成功
            console.log(`update state successfully`)
        }
    })
}

getLatestBuyEvents();

setInterval(() => {
    getLatestBuyEvents();
}, 2000)